package com.yh.threadTest.test;

/**
 * @ClassName Demo7
 * @Description 生产者与消费者
 * @Author 0715-YuHao
 * @Date 2020/11/11 15:20
 */
public class Demo7 {

    public static void main(String[] args) {
        Food f = new Food();
        new Cook(f).start();
        new Waiter(f).start();
    }

    //厨师
    static class Cook extends Thread {
        private Food f;
        public Cook(Food f) {
            this.f = f;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                if (i % 2 == 0) {
                    f.set("辣椒炒肉" + i, "麻辣");
                }else {
                    f.set("水煮牛肉" + i, "香辣");
                }
            }
        }
    }

    //服务员
    static class Waiter extends Thread {
        private Food f;
        public Waiter(Food f) {
            this.f = f;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                f.get();
            }
        }
    }

    //食物
    static class Food {
        private String name;
        private String taste;

        public synchronized void get() {
            System.out.println("服务员端走的菜是" + name + "，味道:" + taste);
            this.notifyAll();
            try {
                this.wait(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public synchronized void set(String name, String taste) {
            this.name = name;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.taste = taste;
            this.notifyAll();
            try {
                this.wait(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
